package app.nexd.com.indoor.presenter;

import android.content.Context;
import android.graphics.Color;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;

import java.util.List;

import app.nexd.com.indoor.R;
import app.nexd.com.indoor.activity.inter.IBDMapViewActivity;
import app.nexd.com.indoor.presenter.inter.IRoutePlanPresenter;

/**
 * Created by lawrence on 2015/12/17.
 */
public class IRoutePlanPresenterImpl implements IRoutePlanPresenter {

    private IBDMapViewActivity ibdMapViewActivity;
    private MapView mapView;
    private Context context;
    private LocationClient locationClient;
    private MyLocationListener myLocationListener;
    private boolean isFirstLocation = false;
    // 百度地图的路径规划对象
    private RoutePlanSearch routePlanSearch;
    // 上次点的集合的尾巴
    private LatLng lastLastLatLng;

    public IRoutePlanPresenterImpl(IBDMapViewActivity ibdMapViewActivity, MapView mapView, Context context) {
        this.ibdMapViewActivity = ibdMapViewActivity;
        this.mapView = mapView;
        this.context = context;
        this.locationClient = new LocationClient(context);
        this.myLocationListener = new MyLocationListener();
        this.routePlanSearch = RoutePlanSearch.newInstance();
        this.locationClient.registerLocationListener(myLocationListener);
    }

    @Override
    public void designRoutePlan(LatLng start, final LatLng end) {
        // 添加起点图标
        BitmapDescriptor startBitMap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_st);
        OverlayOptions startOverlay = new MarkerOptions()
                .position(start)
                .title("起点")
                .icon(startBitMap);
        ibdMapViewActivity.addOverlay(startOverlay);

        // TODO  通过起点和终点坐标， 分别设置起点和终点图片
        final WalkingRoutePlanOption walkingRoutePlanOption = new WalkingRoutePlanOption();
        walkingRoutePlanOption.from(PlanNode.withLocation(start)).to(PlanNode.withLocation(end));
        if (routePlanSearch.walkingSearch(walkingRoutePlanOption)) {
            routePlanSearch.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
                @Override
                public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

                    if (walkingRouteResult == null || walkingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                        ibdMapViewActivity.showToast("抱歉，未找到结果");
                    }
                    if (walkingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                        //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
//                        walkingRouteResult.getSuggestAddrInfo();
                        return;
                    }
                    if (walkingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                        List<WalkingRouteLine> lines = walkingRouteResult.getRouteLines();
                        OverlayOptions option = null;
                        lastLastLatLng = null;
                        for (WalkingRouteLine walkingRouteLine : lines) {
                            List<WalkingRouteLine.WalkingStep> steps = walkingRouteLine.getAllStep();
                            for (WalkingRouteLine.WalkingStep step : steps) {
                                List<LatLng> latLngs = step.getWayPoints();
                                if (lastLastLatLng == null) {
                                    lastLastLatLng = latLngs.get(latLngs.size() - 1);
                                } else {
                                    latLngs.add(0, lastLastLatLng);
                                    lastLastLatLng = latLngs.get(latLngs.size() - 1);
                                }
                                option = new PolylineOptions()
                                        .color(Color.BLUE)
                                        .dottedLine(false)
                                        .points(latLngs)
                                        .width(10)
                                        .visible(true);
                                ibdMapViewActivity.addOverlay(option);
                            }
                        }
                    }
                }

                @Override
                public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

                }

                @Override
                public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

                }
            });
        } else {
            ibdMapViewActivity.showToast("未找到相应路线");
        }

        // 添加终点图标
        BitmapDescriptor endBitMap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_en);
        OverlayOptions endOverlay = new MarkerOptions()
                .position(end)
                .title("终点")
                .icon(endBitMap);
        ibdMapViewActivity.addOverlay(endOverlay);
    }

    @Override
    public void initMap() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 3000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(false);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        option.setLocationNotify(true);
        locationClient.setLocOption(option);
    }

    @Override
    public void startLocation() {
        locationClient.start();
    }

    @Override
    public void stopLocation() {
        locationClient.stop();
    }


    private class MyLocationListener implements BDLocationListener {

        MapStatusUpdate u = null;

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100)
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();
            if (isFirstLocation) {
                isFirstLocation = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                u = MapStatusUpdateFactory.newLatLng(ll);
                ibdMapViewActivity.animateMapStatus(u);
            }
            ibdMapViewActivity.setLocationData(locData);
        }
    }
}
